<template>
  <div class="content">
    <div class="head">
      <div class="searchContent">
        <div class="address" @click="selectCity">{{city}} {{" "}}<van-icon name="arrow-down" /></div>
        <van-search v-model="value" placeholder="请输入搜索关键词" :clearable='false' @input='inputValue' />
      </div>
      <van-tabs v-model="tabs" @click="onTabs">
        <van-tab title="热映"></van-tab>
        <van-tab title="影院"></van-tab>
        <van-tab title="即将上映"></van-tab>
      </van-tabs>
    </div>

    <div class="list" v-if="tabs==0" v-for="(item,index) in rotList" :key="index" @click="gotoDetail(item.id)">
      <div class="listContent">
        <img class="contentImg" :src="item.cover" alt="" />
        <div class="contentText">
          <div class="text1">{{item.filmName}}</div>
          <div class="text2">电影评分 <span style="color: #FF6060;">{{item.score/100==0?'暂无评分':item.score/100}}</span></div>
          <div class="text3">导演:{{item.director}}</div>
          <div class="text3">主演:{{item.cast}}</div>
          <div class="text3">类型:{{item.type}}</div>
        </div>
        <div class="button" @click.stop="gotoList(item)">{{item.preSaleFlag==0?'购票':'预售'}}</div>
      </div>
    </div>

    <div v-if="tabs==1">
      <div class="area" @click="selectArea">{{area}} {{" "}}<van-icon name="arrow-down" /></div>
      <div class="areaList" v-for="(item,index) in cinemaList" :key="index" @click="gotoDeatil(item)">
        <div class="areaName">{{item.cinemaName}}</div>
        <div class="areaAddress"><div class="addressText">{{item.address}}</div> <div>{{distance(item.distance)}}</div></div>
      </div>
    </div>
    <div v-if="tabs==2" v-for="(item,index) in saleList" :key="index">
      <div class="listHead">
        <!-- <div class="day">明天</div> -->
        <div class="dayTime">{{item[0].split(',')[0]}}</div>
      </div>
      <div class="list" v-for="(it,idx) in item[1]" :key="idx">
        <div class="listContent">
          <img class="contentImg" :src="it.cover" alt="" />
          <div class="contentText">
            <div class="text1">{{it.filmName}}</div>
            <div class="text2">电影评分 <span style="color: #FF6060;">{{it.score/100==0?'暂无评分':it.score/100}}</span></div>
            <div class="text3">导演:{{it.director}}</div>
            <div class="text3">主演:{{it.cast}}</div>
            <div class="text3">类型:{{it.type}}</div>
          </div>
          <div class="button2"></div>
        </div>
      </div>
    </div>


    <div v-if="isCity" class="popup">
      <van-picker
        title="城市"
        show-toolbar
        :columns="cityList"
        @confirm="cityConfirm"
        @cancel="cityCancel"
      />
    </div>

    <div v-if="isArea" class="popup">
      <van-picker
        title="区域"
        show-toolbar
        :columns="areaList"
        @confirm="areaConfirm"
        @cancel="areaCancel"
      />
    </div>

    <van-tabbar v-model="active" @change="onChange">
        <van-tabbar-item>
          <span>电影/影院</span>
          <template #icon="props">
            <img :src="props.active ? icon.inactive : icon.active" />
          </template>
        </van-tabbar-item>
        <van-tabbar-item>
          <span>个人中心</span>
          <template #icon="props">
            <img :src="props.active ? icon2.active : icon2.inactive" />
          </template>
        </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import {
  setStore,
  getStore,
  removeStore
} from '@/utils/storage'
import axios from 'axios';
import { jsonp } from "vue-jsonp";
import wx from 'weixin-js-sdk'
import json from '@/utils/address.json'
import {Tabbar, TabbarItem} from 'vant';
import {userInfo,GetJsapi,getFilmList,getCinemaList,getDistrict} from '@/api/home.js'
import {parseTime} from "@/utils/index.js"
export default {
  name: "my",
  data() {
    return {
      value:'',
      active: 0,
      tabs:0,
      icon: {
        active: 'https://open-cards-1302786294.cos.ap-guangzhou.myqcloud.com/images/20240624/cfc39318b3da43c1a67e675e21a6bc6f.png',
        inactive: 'https://open-cards-1302786294.cos.ap-guangzhou.myqcloud.com/images/20240624/7180fa59cbd94a559eb62b5b177eb2e7.png',
      },
      icon2: {
        active: 'https://open-cards-1302786294.cos.ap-guangzhou.myqcloud.com/images/20240624/b6b47815fe6f42fba08420bfdce47ff6.png',
        inactive: 'https://open-cards-1302786294.cos.ap-guangzhou.myqcloud.com/images/20240624/a589c4f9784e4da49e32b53531c29e92.png',
      },
      isCity:false,
      isArea:false,
      cityList:[], //城市列表
      areaList:[], //当前城市区域列表
      rotList:[], //热门
      saleList:[], //预售
      addressInfo:{},
      city:'长沙市', //当前城市
      citycode:'', //当前城市编码
      areaCodeList:[], //当前城市区域编码列表
      areacode:'', //当前区域编码,
      area:'',
      cinemaList:[],
      timer:null
    };
  },
  mounted() {
    console.log(this.$route)
    if(this.$route.query.systemCode){
      setStore('systemCode',this.$route.query.systemCode)
    }
    if(this.$route.query.data){
      setStore('data',this.$route.query.data)
    }
    if(!getStore('addressInfo')){
      this.onLoad()
    }else if(getStore('selectCity')){
      this.city = getStore('selectCity')
      this.areacode = getStore('areacode')
      this.citySelect()
    }else{
      this.city = JSON.parse(getStore('addressInfo')).address_component.city
      this.area = JSON.parse(getStore('addressInfo')).address_component.district
      this.areacode = JSON.parse(getStore('addressInfo')).ad_info.adcode
      this.citySelect()
    }
    this.timer = null
    this.userInfo()
  },
  methods: {
    distance(item){
      console.log(item)
      return item>1000?Number(item/1000).toFixed(2)+'km':item+'m'
    },
    userInfo(){
      userInfo().then(res=>{
        setStore('userInfo', res.data)
      })
    },
    onChange(index){
      if(index==1){
        this.$router.push({
          path:'/my'
        })
      }
    },
    //去选座
    gotoDeatil(item){
      this.$router.push({
        path:'/cinemaDetail?item='+JSON.stringify(item)
      })
    },
    //去详情
    gotoDetail(id){
      this.$router.push({
        path:'/Detail?id='+id
      })
    },
    //根据电影寻找影院列表
    gotoList(e){
      console.log(e.filmCode)
      this.$router.push({
        path:'/cinemaList?filmCode='+e.filmCode
      })
    },
    // 影片列表
    getFilmList(index){
      let data = {
        name:this.value,
        publishFlag:index,
        cityId:this.citycode,
        limit:99999
      }
      getFilmList(data).then(res=>{
        console.log(res)
        if(index==0){
          this.rotList = res.page.records
        }else{
          let list = res.page.records
          this.saleList = this.groupBy(list,'publishDate')
          console.log(this.saleList)
        }

      })
    },
    // 影院列表
    getCinemaList(){
      let data = {
        cityId : this.citycode,
        countyId : this.areacode,
        name : this.value,
        limit:99999,
        location:JSON.parse(getStore('addressInfo')).location.lat+' '+JSON.parse(getStore('addressInfo')).location.lng
      }
      getCinemaList(data).then(res=>{
        console.log(res)
        this.cinemaList = res.page.records
      })
    },
    groupBy(list, key) {
      return list.reduce((acc, item) => {
        let x = new Date(item.publishDate * 1000);
        item.publishDate = x.getMonth() + 1+ "月"+x.getDate()+"日" +','+ this.getWeekday(x)
          const groupKey = item[key];
        if (!acc.has(groupKey)) {
          acc.set(groupKey, []);
        }
        acc.get(groupKey).push(item);
        return acc;
      }, new Map());
    },
    getWeekday(date) {
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const dayIndex = date.getDay();
        return weekdays[dayIndex];
    },
    onTabs(){
      console.log(this.tabs)
      if(this.tabs==0){
        this.getFilmList(0)
      }else if(this.tabs==1){
        this.getCinemaList()
      }else{
        this.getFilmList(1)
      }
    },
    selectCity(){
      this.isCity = true
    },
    cityConfirm(e){
      this.cityCode(e)
      this.isCity = false
      this.city = e
      removeStore('selectArea')
      setStore('selectCity',this.city)
    },
    cityCancel(){
      this.isCity = false
    },
    selectArea(){
      this.isArea = true
    },
    areaConfirm(e){
      this.areaCode(e)
      this.isArea = false
      this.area = e
      setStore('selectArea',this.area)
    },
    areaCancel(){
      this.isArea = false
    },
    //输入内容
    inputValue(e){
      this.debounceSearch();
    },
    debounceSearch() {
      // 清除之前的定时器
      clearTimeout(this.timer);

      // 设置新的定时器
      this.timer = setTimeout(() => {
        if(this.tabs==0){
          this.getFilmList(0)
        }else if(this.tabs==1){
          this.getCinemaList()
        }else{
          this.getFilmList(1)
        }
      }, 500); // 设置防抖的时间间隔，例如500毫秒
    },
    // 微信地图定位sdk
    onLoad() {
      const that = this
      // 微信SDK配置
      const data = {
        url: location.href.split('#')[0]
      }
      GetJsapi(data)
        .then(res => {
          const resData = res
          wx.config({
            debug: false,
            appId: resData.appId, // 必填,公众号的唯一标识
            timestamp: resData.timestamp, // 必填,生成签名的时间戳
            nonceStr: resData.nonceStr, // 必填,生成签名的随机串
            signature: resData.signature, // 必填,签名
            jsApiList: ['scanQRCode', 'openLocation', 'getLocation'] // 必填,需要使用的JS接口列表
          })
        })
        .catch(res => {
          return res
        })
      wx.ready(function() {
        console.log('初始化js-sdk成功');
        // config信息验证成功后会执行ready方法,所有接口调用都必须在config接口获得结果之后
        // config 是一个客户端的异步操作,所以如果需要在页面加载时调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行.对于用户触发是才调用的接口,则可以直接调用,不需要放在ready函数中
        wx.checkJsApi({
          // 判断当前客户端版本是否支持指定JS接口
          jsApiList: ['scanQRCode', 'openLocation', 'getLocation'],
          success: function(res) {
            // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
            if (res.checkResult.getLocation === true) {
              that.getLocation()
            } else {
              return false
            }
          },
          fail: function(res) {
            // 检测getNetworkType该功能失败时处理
            console.log('fail:' + res)
            return false
          }
        })
      })
    },
    // 重新定位
    getLocation() {
      console.log(1)
      const that = this
      // 判断定位城市
      wx.getLocation({
        type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02','wgs84'
        success: function(res) {
          jsonp('https://apis.map.qq.com/ws/geocoder/v1', {
              location: res.latitude+','+res.longitude,
              key: "FNHBZ-JQ2CD-BQS4B-HY3D2-2BUTQ-TZBXN",
              output: "jsonp"
          }).then(data => {
            console.log(data)
            that.addressInfo = data.result
            setStore('addressInfo', data.result)
            that.city = data.result.address_component.city
            that.area = data.result.address_component.district
            that.areacode = data.result.ad_info.adcode
            that.citySelect()
          })
        },
        fail: function(res) {
          // 检测getNetworkType该功能失败时处理
          // console.log('fail:' + res)

        }
      })
    },
    //获取城市列表
    citySelect(){
      getDistrict().then(res=>{
        let jsonList = Object.entries(JSON.parse(res.data).child)
        jsonList.forEach((item,index)=>{
          this.cityList.push(item[1].name)
        })
        this.cityCode(this.city)
      })

    },
    //获取城市编码和区域列表
    cityCode(e){
      this.areaList = []
      this.areaCodeList = []
      let jsonList = Object.entries(json.child)
      jsonList.forEach((item,index)=>{
        if(item[1].name==e){
          this.citycode=item[0]
          Object.entries(item[1].child).forEach((it,idx)=>{   //根据城市获取区域列表
            this.areaList.push(it[1])
            this.areaCodeList.push(it[0])  //根据城市获取区域编码列表 数据对应区域列表
          })
        }
      })
      if(getStore('selectArea')){
        this.area = getStore('selectArea')
      }else{
        this.area = this.areaList[0]
        this.areaList.forEach((item,index)=>{
          if(item == this.area){
            console.log(index,this.areaCodeList)
            this.areacode = this.areaCodeList[index]
            setStore('areacode',this.areacode)
          }
        })
      }

      if(this.tabs==1){
        this.getCinemaList()
      }else{
        this.getFilmList(0)
      }
    },
    //获取区域编码
    areaCode(e){
      this.areaList.forEach((item,index)=>{
        if(item == e){
          this.areacode = this.areaCodeList[index]
          setStore('areacode',this.areacode)
        }
      })
      this.getCinemaList()
    }
  },
  watch: {},
};
</script>

<style scoped lang="scss">
  .content{
    min-width: 100vw;
    min-height: 100vh;
    background-color: #EBF2FC;
    overflow: hidden;
    box-sizing: border-box;
    padding-bottom: 100px;
    .head{
      width: 100%;
      height: 94px;
      background-color: #fff;
      overflow: hidden;
      .searchContent{
        width: 100%;
        height: 28px;
        margin-top: 18px;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        padding: 0 12px;
        overflow: hidden;
        .address{
          font-weight: bold;
          font-size: 13px;
          color: #333333;
          white-space: nowrap
        }
        .van-search{
          height: 28px;
        }
      }
    }

    .listHead{
      margin-left: 25px;
      margin-top: 10px;
      .day{
        font-weight: 500;
        font-size: 12px;
        color: #AFAFAF;
      }
      .dayTime{
        font-weight: 500;
        font-size: 16px;
        color: #333333;
      }
    }
    .list{
      width: 353px;
      height: 129px;
      background-color: #fff;
      border-radius: 5px;
      margin: 10px auto 0;
      .listContent{
        width: 100%;
        height: 129px;
        box-sizing: border-box;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #EBEBEB;
        .contentImg{
          display: block;
          width: 74px;
          height: 97px;
        }
        .contentText{
          margin-left: 9px;
          width: 168px;
          overflow: hidden;
          .text1{
            font-weight: bold;
            font-size: 15px;
            color: #333333;
            margin-top: 7px;
            width: 168px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .text2{
            font-weight: bold;
            font-size: 12px;
            color: #333333;
            margin-top: 7px;
            width: 168px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .text3{
            font-weight: 400;
            font-size: 12px;
            color: #757171;
            margin-top: 5px;
            width: 168px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
      .button{
        width:61px;
        height: 28px;
        background-color: #1484FB;
        text-align: center;
        line-height: 28px;
        font-weight: 400;
        font-size: 13px;
        color: #FFFFFF;
        border-radius: 15px;
      }
      .button2{
        width: 50px;
        height: 23px;
        background-color: #FD564D00;
        text-align: center;
        line-height: 24px;
        font-weight: 400;
        font-size: 13px;
        color: #FFFFFF;
        border-radius: 10px;
      }
    }
    .area{
      width: 100%;
      height: 33px;
      background-color: #fff;
      box-sizing: border-box;
      padding-left: 15px;
      font-weight: bold;
      font-size: 15px;
      color: #333333;
      border-top: 1px solid #CCCCCC27;
      padding-top: 6px;
    }
    .areaList{
      width: 355px;
      min-height: 73px;
      background-color: #fff;
      margin: 12px auto 0;
      border-radius: 5px;
      box-sizing: border-box;
      padding: 10px 12px;
      overflow: hidden;
      .areaName{
        font-weight: bold;
        font-size: 17px;
        color: #333333;
        margin-top: 7px;
      }
      .areaAddress{
        font-weight: 500;
        font-size: 12px;
        color: #737373;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .addressText{
          width: 260px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .popup{
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(0, 0, 0, .3);
      z-index: 999;
      .van-picker{
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
      }
    }
    ::v-deep .van-tabs__line{
      background-color: #1484FB !important;
    }
  }
</style>
